<template>
<!-- 
组件说明：
   im组件
 -->
<div>
    <div></div>
</div>    
</template>
<script>
import {
    ws,showChat,createApply, deleteChat, createChat, updateChat, friendList, deleteFriend, messageList, imageUrl,applyList,updateApply
  } from '../api/api';
import { post, fetch, patch, put } from '../common/js/http.js';
export default {
    name: 'webim',
    data: function() {	
        return {
            innerHTML: '',
            chat_id:''
        }
    },
    mounted() {
        this.$store.commit('setPage', 2);//设置需要预请求的参数
        this.openConnect();
        // this.system();
    },
    /** 
     * 
     *  */ 
    methods: {
       // 开启ws链接
      openConnect () {
        let token = window.localStorage.getItem('access_token')
        this.socket = new WebSocket(`${ws}?token=${token}`)
        // this.onMessage
        this.socket.onopen = this.onConnect
        this.socket.onmessage = this.onMessage
        this.socket.onclose = this.onClose
        this.socket.onerror = this.onError
      },
      onError () {
        this.$confirm('聊天服务器连接失败', '提示', {
          confirmButtonText: '重新连接',
          cancelButtonText: '取消',
          type: 'error'
        }).then(() => {
          this.openConnect()
        }).catch(() => {
          localStorage.setItem('token', '')
          this.$router.push('/')
        })
      },
       // 链接成功事件
      onConnect (ws) {
        // this.$message.success(`已成功连接到聊天服务器`)
        this.isConnect = true
      },
      // 断开连接触发函数
      onClose () {
        this.isConnect = false
      },
      // 接受消息事件
      onMessage (ws) {
        try {
            let data = JSON.parse(ws.data);
            // console.log('im接受消息事件',ws);
             // console.log('im状态',data);
          switch (data.type) {
          case 'chatList': // 聊天列表
            this.handleMsgNew(data.chatList);
            this.systemMsgNew(data.systemList);
            break
          case 'msg':
            this.handleMsg(data)
            break
          case 'forbidden':  // token不正确
            this.handleLoginOut()
            break
          case 'repeat':  // 被踢
            this.visible.reConnect = false
            this.socket.close()
            localStorage.setItem('token', '')
            this.$alert('你的账号已在别处登陆', '提示', {
              confirmButtonText: '确定',
              callback: () => {
                this.$router.push('/')
              }
            })
            break
          case 'newApply':   // 有新的好友申请
            this.haveNotReadApply = true
            break
          case 'applySucc':  // 好友申请被同意
            this.handleFriendList()
            this.$message.success('"' + data.friend.username + '"已经同意你的好友申请')
            break
          case 'newGroup': // 接受新群组
            this.chatList.unshift(data.group)
            break
          case 'repeatConnect': // 重复连接
            this.socket.close()
            this.visible.repeatConnect = true
            this.visible.reConnect = false
            break
          case 'goOnline':  // 上线消息
            let chat = this.chatList.find(element => parseInt(element.chat_id) === parseInt(data.chatId))
            chat.online = true
            break
          case 'goOffLine':  // 下线消息
            chat = this.chatList.find(element => parseInt(element.chat_id) === parseInt(data.chatId))
            chat.online = false
            break
          case 'quitGroup':   // 退出群组消息
            const chatId = data.chatId
            const userId = data.userId
            chat = this.chatList.find((element) => parseInt(element.chat_id) === parseInt(chatId))
            const index = chat.userList.findIndex(element => parseInt(element.id) === parseInt(userId))
            const user = chat.userList.splice(index, 1)
            this.$message.success(`<${user.username}>退出了群组<${chat.group_name}>`)
            break
        }
        } catch (err) {
            console.log(JSON.stringify(err));
        }
      },
       // webSocket发送消息
      send (msg) {
        return new Promise((resolve, reject) => {
          if (this.socket.readyState === WebSocket.OPEN) {
            this.socket.send(JSON.stringify(msg))
            resolve()
          } else {
            this.isConnect = false;
            reject(new Error())
          }
        })
      },
    system (message='im系统消息') {

        console.log('系统消息是否进来了',message);

        //首先第一步添加好友 创建通道
        let access_token = window.localStorage.getItem('access_token');
        let chat_id = window.localStorage.getItem('chat_id');
        // console.log('chat_id',chat_id);
        //发送demo
        // showChat({chat_id:chat_id}).then(res =>{
        //     console.log('查看聊天对象:',res);          
        // })

        /*
           首页判断当前用户是否有聊天对象
           如果存在聊天对象则已经是老用户
           则是新用户需要帮用户创建一个聊天对象
         */
        if(chat_id){
            showChat().then(res =>{
              // console.log('查看聊天对象:',res);
              let chat = res.chat;
              //这里需要加一个查看当前聊天对象id
              let msg = {
                          chat_id: chat_id,
                          msg: message,
                          type: 'msg',
                          msg_type: 0,
                          from_id: chat.target_id,
                          to_id: chat.id,
                          is_read: 1,
                          avatar: ''
                        }
                // console.log(msg);
               this.send(msg).then(() => {
                    // this.$systemlist.push(msg);
                    console.log('第三步发送成功');
                })            
            })
            

        }else{

            createApply({targetId: 0,reason:'系统消息',access_token: access_token,system:1}).then(res => {
                  //需要返回一个
                  console.log('第一步添加系统为好友',res);
                  if (parseInt(res.status) === 1) {
                    //创建聊天对象
                    createChat({targetId:0}).then( res => {
                        console.log('第二步创建系统为聊天对象');
                        let chat = res.chat;
                        let chat_id = res.chat_id;
                        console.log('chat',chat);
                        let msg = {
                            chat_id: chat_id,
                            msg: message,
                            type: 'msg',
                            msg_type: 0,
                            from_id: chat.target_id,
                            to_id: chat.id,
                            is_read: 1,
                            avatar: ''
                        }
                        window.localStorage.setItem('chat_id', chat_id);
                         this.send(msg).then(() => {
                              // this.$systemlist.push(msg);
                              console.log('第三步发送成功');
                          })
                    })

                  }
              })

        }
        // this.$emit('datadone',message);
      },

    },

    props: ['title', 'desc', 'link', 'imgUrl','Sharing','datadone'],
}
</script>
<style>

</style>